# RISC-V OS Makefile

# 工具链配置
CC = riscv64-unknown-elf-gcc
LD = riscv64-unknown-elf-ld
OBJDUMP = riscv64-unknown-elf-objdump

# 编译选项
CFLAGS = -Wall -O0 -ggdb
CFLAGS += -ffreestanding -nostdlib -nostartfiles
CFLAGS += -march=rv64gc -mabi=lp64

# 源文件
KERNEL_SRCS = \
	kernel/boot/entry.S \
	kernel/boot/start.c \
	kernel/drivers/uart.c

# 目标文件
KERNEL_OBJS = $(KERNEL_SRCS:.c=.o)
KERNEL_OBJS := $(KERNEL_OBJS:.S=.o)

# 默认目标：构建内核
all: kernel.elf

# 生成内核ELF文件
kernel.elf: $(KERNEL_OBJS) kernel.ld
	$(LD) -T kernel.ld -o $@ $(KERNEL_OBJS)
	@echo "=== 内核构建完成 ==="
	$(OBJDUMP) -S $@ > kernel.asm
	$(OBJDUMP) -t $@ > kernel.sym

# 编译汇编文件
%.o: %.S
	$(CC) $(CFLAGS) -c -o $@ $<

# 编译C文件  
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

# 运行QEMU
qemu: kernel.elf
	@echo "=== 启动QEMU ==="
	qemu-system-riscv64 -machine virt -bios none -kernel kernel.elf -nographic

# 调试模式运行
qemu-gdb: kernel.elf
	@echo "=== 启动QEMU (GDB模式) ==="
	qemu-system-riscv64 -machine virt -bios none -kernel kernel.elf -nographic -s -S

# 清理构建文件
clean:
	rm -f $(KERNEL_OBJS) kernel.elf kernel.asm kernel.sym
	@echo "=== 清理完成 ==="

# 查看内核信息
info: kernel.elf
	@echo "=== 内核信息 ==="
	file kernel.elf
	@echo "=== 段信息 ==="
	$(OBJDUMP) -h kernel.elf
	@echo "=== 符号表 ==="
	$(OBJDUMP) -t kernel.elf | grep -E "(main|_entry|uart)"

.PHONY: all qemu clean info
